package com.ar4j.type;

import java.io.Serializable;
import java.util.Date;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

/**
 * This wrapper class truncates the milliseconds off of date
 */
@SuppressWarnings("serial")
public class DateWithoutMillis implements Comparable<DateWithoutMillis>, Serializable {
  private Date date;

  private static long extractTimeMillis(Date date) {
    if (date == null)
      throw new IllegalArgumentException("date must not be null");
    
    return date.getTime();
  }
  
  /**
   * Same as new ClippedDate(System.currentTimeMillis())
   */
  public DateWithoutMillis() {
    this(System.currentTimeMillis());
  }

  /**
   * Construct with a java Date
   */
  public DateWithoutMillis(Date date) {
    this(extractTimeMillis(date));
  }

  /**
   * Construct with time in milliseconds
   */
  public DateWithoutMillis(long timeInMillis) {
    long sec = timeInMillis / 1000;
    long truncMilliSec = sec * 1000; // quick and dirty
    
    this.date = new Date(truncMilliSec);
  }

  /**
   * @return A copy of internal date to prevent external modification 
   */
  public Date getDate() {
    return new Date(date.getTime());
  }
  
  public long getTime() {
    return date.getTime();
  }

  @Override
  public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
  }

  @Override
  public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
  }
  
  @Override
  public int compareTo(DateWithoutMillis other) {
    return date.compareTo(other.date);
  }

  @Override
  public String toString() {
    return date.toString();
  }
}
